package com.pk.springbootsy1.controller;

import cn.dev33.satoken.annotation.SaCheckRole;
import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.util.SaResult;
import com.pk.springbootsy1.dto.TEquipmentDto;
import com.pk.springbootsy1.entity.TEquipment;
import com.pk.springbootsy1.enums.RoleEnum;
import com.pk.springbootsy1.service.TEquipmentService;
import com.pk.springbootsy1.service.TUserService;
import com.pk.springbootsy1.util.R;
import io.swagger.v3.oas.annotations.Operation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/equipment")
public class TEquipmentController {
    @Autowired
    private TEquipmentService tEquipmentService;
    @Autowired
    private TUserService tUserService;

    //添加设备
    @Operation(summary = "添加设备")
    @PostMapping("/add")
    @SaCheckRole("admin")
    public R<Void> add(@RequestBody TEquipment tEquipment) {
        if (tEquipmentService.save(tEquipment)) {
            return R.ok("添加成功");
        } else {
            return R.fail("添加失败");
        }
    }

    //修改设备
    //回收设备则将设备的userId设置为null
    //分配设备则将设备的userId设置为分配的用户的id
    @Operation(summary = "修改设备")
    @PutMapping()
    @SaCheckRole("admin")
    public R<Void> update(@RequestBody TEquipment tEquipment) {
        if (tEquipmentService.updateById(tEquipment)) {
            return R.ok("修改成功");
        } else {
            return R.fail("修改失败");
        }
    }

    //删除设备
    @Operation(summary = "删除设备")
    @DeleteMapping("/{id}")
    @SaCheckRole("admin")
    public R<Void> delete(@PathVariable Integer id) {
        if (tEquipmentService.removeById(id)) {
            return R.ok("删除成功");
        } else {
            return R.fail("删除失败");
        }
    }

    //查询所有设备
    @Operation(summary = "查询所有设备")
    @GetMapping("/list")
    @SaCheckRole("admin")
    public R<List<TEquipmentDto>> list() {
        return R.ok(tEquipmentService.listTEquipmentDto());
    }

    //查某个用户的设备 看自己名下的设备
    @GetMapping("/{id}")
    @Operation(summary = "查看设备")
    public R<List<TEquipmentDto>> getById(@PathVariable Integer id) {
        if (StpUtil.hasRole(RoleEnum.USER.getMessage())){
            if (StpUtil.getLoginId() ==id) {
                System.out.println(StpUtil.getLoginId());
                return R.fail("无权限");
            }
        }
        if (tUserService.getById(id) == null) {
            return R.fail("用户不存在");
        }
        return R.ok(tEquipmentService.getByUserId(id));
    }

}
